package org.example.tree;

import javax.swing.*;
import java.awt.*;

/**
 * @ClassName QuadtreeDrawer
 * @Description TODO
 * @Author hongjun
 * @Date 2024/5/18 上午12:26
 * @Version 1.0
 */
public class QuadtreeDrawer extends JPanel {
    private Quadtree quadtree;

    public QuadtreeDrawer(Quadtree quadtree) {
        this.quadtree = quadtree;
        this.setPreferredSize(new Dimension(quadtree.getBounds().width, quadtree.getBounds().height));
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        drawQuadtree(g, quadtree);
    }

    private void drawQuadtree(Graphics g, Quadtree node) {
        // 绘制当前节点的边界（可选）
        g.drawRect(node.getBounds().x, node.getBounds().y, node.getBounds().width, node.getBounds().height);

        // 绘制当前节点的阻挡物（如果有的话）
        if (node.getBlocks() != null) {
            for (Block block : node.getBlocks()) {
                g.setColor(Color.RED); // 假设阻挡物用红色表示
                g.fillRect(block.getBounds().x, block.getBounds().y, block.getBounds().width, block.getBounds().height);
            }
        }

        // 如果有子节点，递归绘制它们
        if (node.getNodes() != null) {
            for (Quadtree child : node.getNodes()) {
                drawQuadtree(g, child);
            }
        }
    }

    // 一个简单的方法来显示QuadtreeDrawer在一个JFrame中
    public static void showInFrame(Quadtree quadtree) {
        JFrame frame = new JFrame("Quadtree Drawer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new QuadtreeDrawer(quadtree));
        frame.pack();
        frame.setLocationRelativeTo(null); // 居中显示窗口
        frame.setVisible(true);
    }
}
